package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.apache.tomcat.util.buf.StringUtils;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IFollowService followService;

    private static final String FEED_KEY = "feed:";


    @Override
    public Result queryHotBlog(Integer current) {

        Page<Blog> page = query().orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            // 获取用户信息
            queryBlogUser(blog);

            // 是否点赞过
            isBlogLiked(blog);
        });

        return Result.ok(records);

    }

    @Override
    public Result getByID(String id) {

        Blog blog = getById(id);
        if(blog == null) {
            return Result.fail("不存在");
        }

        // 获取用户信息
        queryBlogUser(blog);

        // 是否点赞过
        isBlogLiked(blog);

        return Result.ok(blog);
    }



    @Override
    public Result likeBlog(Long id) {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();

        // 判断当前博客是否被点赞
        String key = "blog:liked:" + id;

        Double score = redisTemplate.opsForZSet().score(key, userId + "");

        if(score != null) {
            // 点赞过了，从博客的点赞列表中删除当前用户
            boolean ifSuccess = update().setSql("liked=liked - 1").eq("id", id).update();
            if(ifSuccess) {
                redisTemplate.opsForZSet().remove(key, userId+"");
            }

        } else {
            // 没有点赞过，添加到set集合
            boolean ifSuccess = update().setSql("liked=liked + 1").eq("id", id).update();
            if(ifSuccess) {
                // 没有点赞过，添加当前用户到set集合
                redisTemplate.opsForZSet().add(key, userId + "", System.currentTimeMillis());
            }
        }

        return Result.ok();
    }


    @Override
    public Result getBlogLikes(String blogId) {

        // 获取列表的key
        String key = "blog:liked:" + blogId;

        // 获取前五名
        Set<String> range = redisTemplate.opsForZSet().range(key, 0, 4);
        if(range == null || range.size() == 0) {
            return Result.ok(Collections.emptyList());
        }

        // 拿出用户id
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());

        // 转换为字符串
        String idsStr = StrUtil.join(",", ids);
        // 根据用户id查询
        List<UserDTO> result = userService.query()
                // where id in (xxxx) order by field(id, 5,4,3,2,1)
                .in("id", ids).last("order by field(id,"+idsStr+")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());

        return Result.ok(result);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean save = save(blog);

        if(save) {
            // 保存成功，推送到收件箱
            // 获取所有关注了当前博主的用户【查询他所有的粉丝】
            List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
            for (Follow follow : follows) {
                // 获取粉丝的id【注意这个地方是反过来的】
                Long followUserId = follow.getUserId();

                String key = FEED_KEY + followUserId;

                redisTemplate.opsForZSet().add(key, blog.getId() + "", System.currentTimeMillis());

            }
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryFollowBlog(Long lastId, Integer offset) {

        // 直接查询当前用户的收件箱
        String key = FEED_KEY + UserHolder.getUser().getId();

        // 【offset是偏移量，为1表示将查询到的数据往后偏移一位】
        // lastId 是上次查询的最小时间戳
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, lastId, offset, 2);

        if(typedTuples == null || typedTuples.size() == 0) {
            return Result.ok();
        }

        // 后面的这一堆操作主要是为了防止查询出来的数据的最后几条数据的时间戳是一样的，
        // 如果最后几条数据的时间戳是一样的，那么应该记录下来有几条，下次查询就可以偏移这么多条
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1; // 记录分数相同数据的条数
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 获取id
            ids.add(Long.valueOf(typedTuple.getValue()));
            // 获取分数
            long time = typedTuple.getScore().longValue();
            if(time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }

        // 根据id查询
        String idStr = StrUtil.join(",", ids);
        // 博客列表
        List<Blog> blogs = query().in("id", idStr).
                last("order by field(id, " + idStr + ")").list();
        if(blogs == null  || blogs.size() == 0) {
            return Result.ok();
        }

        for (Blog blog : blogs) {
            isBlogLiked(blog);
            //
            queryBlogUser(blog);
        }
        // 封装返回
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(os); // 偏移的数量
        result.setMinTime(minTime); // 本次查询最小的时间戳

        return Result.ok(result);
    }
/*
    // 没有排序的
    @Override
    public Result likeBlog(Long id) {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();

        // 判断当前博客是否被点赞
        String key = "blog:liked:" + id;

        boolean member = redisTemplate.opsForSet().isMember(key, userId + "");

        if(member) {
            // 点赞过了，从博客的点赞列表中删除当前用户
            boolean ifSuccess = update().setSql("liked=liked - 1").eq("id", id).update();
            if(ifSuccess) {
                redisTemplate.opsForSet().remove(key, userId+"");
            }

        } else {
            // 没有点赞过，添加到set集合
            boolean ifSuccess = update().setSql("liked=liked + 1").eq("id", id).update();
            if(ifSuccess) {
                // 没有点赞过，添加当前用户到set集合
                redisTemplate.opsForSet().add(key, userId + "");
            }
        }

        return Result.ok();
    }
*/

    private void isBlogLiked(Blog blog) {
        // 获取当前用户
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            return ;
        }

        // 判断是否已经点赞过了
        String key = "blog:liked:" + blog.getId();

        Double score = redisTemplate.opsForZSet().score(key, user.getId() + "");

        blog.setIsLike(score != null);

        /*        Boolean member = redisTemplate.opsForSet().isMember(key, userId + "");

        blog.setIsLike(Boolean.TRUE.equals(member));*/
    }


    private void queryBlogUser(Blog blog){
        User user = userService.getById(blog.getUserId());
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());

    }
}
